package com.example.controller;

import com.example.pojo.User;
import com.example.service.IUserService;
import com.example.util.R;
import com.example.vo.UserProfile;
import com.example.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户api接口")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public R<UserVO> login(@RequestBody User user){
        UserVO foundUser = userService.login(user.getPhone(), user.getPassword());

        if (foundUser != null){
            return R.success("登录成功", foundUser);
        } else {
            return R.fail("登录失败");
        }
    }

    @ApiOperation("新增用户")
    @PostMapping("/save")
    public R<User> addUser(@RequestBody User user){
        try {
            userService.save(user);
            return R.success("用户添加成功！", user);
        } catch (Exception e) {
            return R.fail("用户添加失败：" + e.getMessage());
        }
    }

    @ApiOperation("删除用户")
    @GetMapping("/remove/{id}")
    public R removeUserById(@PathVariable("id") Long userId){
        try {
            userService.removeById(userId);
            return R.success("用户删除成功", null);
        } catch (Exception e) {
            return R.fail("用户删除失败：" + e.getMessage());
        }
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public R<User> updateUser(@RequestBody User user){
        try {
            userService.updateById(user);
            return R.success("用户修改成功！", user);
        } catch (Exception e) {
            return R.fail("用户修改失败：" + e.getMessage());
        }
    }

    @ApiOperation("查询单个用户信息")
    @GetMapping("/search/{id}")
    public R<User> searchOneUser(@PathVariable("id") Long userId){
        try {
            return R.success("用户查询成功！", userService.getById(userId));
        } catch (Exception e) {
            return R.fail("用户查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("查询全部用户信息")
    @PostMapping("/search/all")
    public R<List<User>> searchUserList(){
        try {
            return R.success("用户查询成功！", userService.findUserList());
        } catch (Exception e) {
            return R.fail("用户查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("获取用户头像和昵称")
    @GetMapping("/profile/{id}")
    public R getUserProfile(@PathVariable("id") Long userId){
        UserProfile userProfile = userService.getUserProfileById(userId);
        if (userId != null){
            return R.success("获取成功", userProfile);
        }else {
            return R.fail("获取失败");
        }

    }



}
